from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QSpinBox, QComboBox, QColorDialog, QPushButton
from PySide6.QtCore import Signal
from PySide6.QtGui import QColor
import json
import os
from logger.manager import LogManager

class TerminalPanel(QWidget):
    terminal_config_changed = Signal(dict)
    
    def __init__(self):
        super().__init__()
        self.log_manager = LogManager()
        self.app_log = self.log_manager.get_log_file_path('app')
        self.config_dir = os.path.expanduser('~/.a-terminal/settings')
        self.config_path = os.path.join(self.config_dir, 'terminal.json')
        self.ensure_config_dir()
        self.init_ui()
        self.setObjectName("terminal_panel")
        
    def ensure_config_dir(self):
        """确保配置目录存在"""
        os.makedirs(self.config_dir, exist_ok=True)
        
    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(16, 16, 16, 16)
        layout.setSpacing(12)
        
        # 字体大小设置
        font_layout = QHBoxLayout()
        font_label = QLabel("字体大小：")
        self.font_size = QSpinBox()
        self.font_size.setRange(8, 72)
        self.font_size.setValue(self.load_config().get('fontSize', 14))
        self.font_size.valueChanged.connect(self.on_config_changed)
        font_layout.addWidget(font_label)
        font_layout.addWidget(self.font_size)
        font_layout.addStretch()
        layout.addLayout(font_layout)
        
        # 光标样式设置
        cursor_layout = QHBoxLayout()
        cursor_label = QLabel("光标样式：")
        self.cursor_style = QComboBox()
        self.cursor_style.addItems(["block", "underline", "bar"])
        self.cursor_style.setCurrentText(self.load_config().get('cursorStyle', 'block'))
        self.cursor_style.currentTextChanged.connect(self.on_config_changed)
        cursor_layout.addWidget(cursor_label)
        cursor_layout.addWidget(self.cursor_style)
        cursor_layout.addStretch()
        layout.addLayout(cursor_layout)
        
        # 主题颜色设置
        theme = self.load_config().get('theme', {})
        
        # 背景色
        bg_layout = QHBoxLayout()
        bg_label = QLabel("背景颜色：")
        self.bg_color = QPushButton()
        self.bg_color.setFixedSize(60, 24)
        self.bg_color.clicked.connect(lambda: self.choose_color('background'))
        self.update_color_button(self.bg_color, theme.get('background', '#FFFFFF'))
        bg_layout.addWidget(bg_label)
        bg_layout.addWidget(self.bg_color)
        bg_layout.addStretch()
        layout.addLayout(bg_layout)
        
        # 前景色
        fg_layout = QHBoxLayout()
        fg_label = QLabel("前景颜色：")
        self.fg_color = QPushButton()
        self.fg_color.setFixedSize(60, 24)
        self.fg_color.clicked.connect(lambda: self.choose_color('foreground'))
        self.update_color_button(self.fg_color, theme.get('foreground', '#000000'))
        fg_layout.addWidget(fg_label)
        fg_layout.addWidget(self.fg_color)
        fg_layout.addStretch()
        layout.addLayout(fg_layout)
        
        # 光标颜色
        cursor_color_layout = QHBoxLayout()
        cursor_color_label = QLabel("光标颜色：")
        self.cursor_color = QPushButton()
        self.cursor_color.setFixedSize(60, 24)
        self.cursor_color.clicked.connect(lambda: self.choose_color('cursor'))
        self.update_color_button(self.cursor_color, theme.get('cursor', '#000000'))
        cursor_color_layout.addWidget(cursor_color_label)
        cursor_color_layout.addWidget(self.cursor_color)
        cursor_color_layout.addStretch()
        layout.addLayout(cursor_color_layout)
        
        # 选择文本背景色
        selection_bg_layout = QHBoxLayout()
        selection_bg_label = QLabel("选择文本背景色：")
        self.selection_bg_color = QPushButton()
        self.selection_bg_color.setFixedSize(60, 24)
        self.selection_bg_color.clicked.connect(lambda: self.choose_color('selectionBackground'))
        self.update_color_button(self.selection_bg_color, theme.get('selectionBackground', '#3297FD'))
        selection_bg_layout.addWidget(selection_bg_label)
        selection_bg_layout.addWidget(self.selection_bg_color)
        selection_bg_layout.addStretch()
        layout.addLayout(selection_bg_layout)
        
        # 选择文本前景色
        selection_fg_layout = QHBoxLayout()
        selection_fg_label = QLabel("选择文本前景色：")
        self.selection_fg_color = QPushButton()
        self.selection_fg_color.setFixedSize(60, 24)
        self.selection_fg_color.clicked.connect(lambda: self.choose_color('selectionForeground'))
        self.update_color_button(self.selection_fg_color, theme.get('selectionForeground', '#FFFFFF'))
        selection_fg_layout.addWidget(selection_fg_label)
        selection_fg_layout.addWidget(self.selection_fg_color)
        selection_fg_layout.addStretch()
        layout.addLayout(selection_fg_layout)
        
        layout.addStretch()
        
    def load_config(self):
        try:
            if os.path.exists(self.config_path):
                with open(self.config_path, 'r', encoding='utf-8') as f:
                    return json.load(f)
        except Exception as e:
            self.log_manager.write_log(self.app_log, f"加载终端配置失败: {str(e)}", "Terminal")
        return {"fontSize": 14, "theme": {"background": "#FFFFFF", "foreground": "#000000", "cursor": "#000000", "selectionBackground": "#3297FD", "selectionForeground": "#FFFFFF"}, "cursorStyle": "block"}
    
    def save_config(self):
        try:
            config = {
                "fontSize": self.font_size.value(),
                "theme": {
                    "background": self.bg_color.property('color'),
                    "foreground": self.fg_color.property('color'),
                    "cursor": self.cursor_color.property('color'),
                    "cursorAccent": self.cursor_color.property('color'),
                    "selectionBackground": self.selection_bg_color.property('color'),
                    "selectionForeground": self.selection_fg_color.property('color')
                },
                "cursorStyle": self.cursor_style.currentText()
            }
            with open(self.config_path, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=4)
            self.terminal_config_changed.emit(config)
            self.log_manager.write_log(self.app_log, "终端配置已保存", "Terminal")
            
            return True
        except Exception as e:
            self.log_manager.write_log(self.app_log, f"保存终端配置失败: {str(e)}", "Terminal")
            return False
    
    def update_color_button(self, button, color):
        button.setProperty('color', color)
        button.setStyleSheet(f"background-color: {color}; border: 1px solid #999;")
    
    def choose_color(self, color_type):
        # 创建颜色类型到按钮变量名的映射
        color_button_map = {
            'background': 'bg_color',
            'foreground': 'fg_color',
            'cursor': 'cursor_color',
            'selectionBackground': 'selection_bg_color',
            'selectionForeground': 'selection_fg_color'
        }
        
        # 获取对应的按钮变量名
        button_name = color_button_map.get(color_type)
        if not button_name:
            self.log_manager.write_log(self.app_log, f"未知的颜色类型: {color_type}", "Terminal")
            return
            
        button = getattr(self, button_name)
        current_color = QColor(button.property('color'))
        # 使用exec_方法替代getColor静态方法，确保对话框模态显示
        color_dialog = QColorDialog(current_color, self)
        color_dialog.setWindowTitle(f"选择{color_type}颜色")
        if color_dialog.exec():
            color = color_dialog.selectedColor()
            if color.isValid():
                self.update_color_button(button, color.name())
                self.on_config_changed()
    
    def on_config_changed(self, *args):
        self.save_config()
        pass